package com.ship.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.exception.BusException;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.contract.bean.ConLabel;
import com.ship.contract.mapper.ConLabelMapper;
import com.ship.contract.service.ConAllLabelService;
import com.ship.contract.service.ConLabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author tangshixuan
 * @date 2023-9-1
 */
@Service
public class ConLabelServiceImpl extends BaseServiceImpl<ConLabelMapper, ConLabel> implements ConLabelService {

    @Autowired
    private ConLabelMapper conLabelMapper;

    @Autowired
    private ConAllLabelService conAllLabelService;

    @Override
    public void saveCon(ConLabel conLabel) {
        String labelValue = conLabel.getLabelValue();
        if(StringUtils.isBlank(labelValue)){
            throw new BusException("标签值不能为空！", BaseResultCode.GENERAL_ERROR);
        }
        if(isExistName(labelValue,null)){
            throw new BusException(labelValue + "标签已存在！", BaseResultCode.GENERAL_ERROR);
        }
        super.save(conLabel);
    }

    @Override
    public void updateConLabel(ConLabel conLabel) {
        String labelValue = conLabel.getLabelValue();
        if(StringUtils.isBlank(labelValue)){
            throw new BusException("标签值不能为空！", BaseResultCode.GENERAL_ERROR);
        }
        if(isExistName(labelValue,conLabel.getId())){
            throw new BusException(labelValue + "标签已存在！",BaseResultCode.GENERAL_ERROR);
        }
        conAllLabelService.updateByLabelId(conLabel.getId(),conLabel.getLabelValue());
        super.updateById(conLabel);
    }

    private boolean isExistName(String labelValue,Long id){
        QueryWrapper<ConLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label_value",labelValue);
        ConLabel existByName = super.getOne(queryWrapper);
        if(existByName != null){
            if(id == null || (id != null && !existByName.getId().equals(id))){
                return true;
            }
        }
        return false;
    }
}
